/*global $Client*/
import React, { useState, useEffect, useCallback } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Checkbox,
  Button,
  Grid,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Typography,
  TablePagination
} from '@mui/material';
import { getCrmRecordFromSql } from "../../util/util";


// 定义列配置
const columns = [
  { id: 'Subject', label: '编号' },
  { id: 'customername', label: '客户简称' },
  { id: 'ContractDate', label: '合同日期' },
  { id: 'AccountOrderNo', label: '客户订单号' },
  { id: 'ownername', label: '所有者' },
];

const App = (pagedata) => {
  const [selectedRows, setSelectedRows] = useState([]);
  const [rows, setRows] = useState([]); // 存储数据的状态
  const [loading, setLoading] = useState(false); // 用于显示加载状态
  const [error, setError] = useState(null); // 用于显示错误
  const [openDialog, setOpenDialog] = useState(false);
  const [dialogMessage, setDialogMessage] = useState('');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  // 获取数据的函数
  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      console.log('pagedata',pagedata);
      let Exportcontractnumberid = pagedata?.data?.data?.Exportcontractnumberid;
      let id1 = pagedata?.data?.data?.id1;
      let modulename = pagedata?.data?.modulename;
      let showsql = pagedata?.data?.showsql;
      
      // let userinfo = await window.ZOHO.CRM.CONFIG.getCurrentUser();

      let responsedata = await getCrmRecordFromSql(showsql); // 获取数据
      console.log('responsedata', responsedata);
      if(responsedata && responsedata.length > 0){
        
      // const conids = responsedata.map(item => item.id);
      // const idsForInClause = conids.map(id => `'${id}'`).join(', ');

      if (modulename === 'CustomModule15') {    //生产发货通知单
        //去除已经做过的单据
        const filteredresponsedata = responsedata.filter(item => {
          const totalPSQty = item.TotalPSQty ? item.TotalPSQty : 0;
          return totalPSQty < item.field17;
        });
        console.log('filteredresponsedata',filteredresponsedata);
        setRows(filteredresponsedata); // 设置所有数据
        if (Exportcontractnumberid) {
          let ids = Exportcontractnumberid.split(',').map(id => id.trim());
          let selected = filteredresponsedata.filter(row => ids.includes(row.id));
          setSelectedRows(selected);
        }
      } else if (modulename === 'CustomModule17') {   //备货
        //去除已经做过的单据
        const filteredresponsedata = responsedata.filter(item => {
          const totalSNQty = item.TotalSNQty ? item.TotalSNQty : 0;  //合计已备货通知数量
          const totalPSQty = item.TotalPSQty ? item.TotalPSQty : 0;  //合计已生产通知数量
          const field17 = item.field17 ? item.field17 : 0;  //合计 数量
          return totalSNQty < field17 && totalPSQty > 0;
        });
        console.log('filteredresponsedata',filteredresponsedata);
        setRows(filteredresponsedata); // 设置所有数据

        if (id1) {
          let ids = id1.split(',').map(id => id.trim());
          let selected = responsedata.filter(row => ids.includes(row.id));
          setSelectedRows(selected);
        }
      }
      }else{
        setRows([]); // 设置所有数据
      }
    } catch (err) {
      setError(err);
      console.error('Error fetching data:', err);
    } finally {
      setLoading(false);
    }
  }, [pagedata]);

  // 在组件加载时调用 fetchData
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 处理多选
  const handleSelectRow = (row) => {
    const isSelected = selectedRows.some(selectedRow => selectedRow.id === row.id);
    let newSelected = [];

    if (!isSelected) {
      newSelected = newSelected.concat(selectedRows, row);
    } else {
      newSelected = selectedRows.filter(selectedRow => selectedRow.id !== row.id);
    }
    setSelectedRows(newSelected);
  };

  // 判断行是否被选中
  const isSelected = (id) => selectedRows.some(row => row.id === id);

  // 处理确定和取消按钮的点击事件
  const handleConfirm = () => {
    const allSameCustomer = selectedRows.every(item => item.Account === selectedRows[0].Account);

    if (!allSameCustomer) {
      setDialogMessage('请确保选择的合同都属于同一个客户。');
      setOpenDialog(true);
    } else {
      $Client.close({ "selectedRows": selectedRows });
    }
  };

  const handleCancel = () => {
    $Client.close();
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
  };

  const handleCancelDialog = () => {
    handleCloseDialog();
  };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  if (loading && rows.length === 0) {
    return (
      <Grid container justifyContent="center" alignItems="center" style={{ height: '100vh' }}>
        <CircularProgress />
      </Grid>
    ); // 加载状态
  }
  if (error) {
    return (
      <Grid container justifyContent="center" alignItems="center" style={{ height: '100vh' }}>
        <p style={{ textAlign: 'center' }}>发生错误，请重试！</p>
      </Grid>
    ); // 错误状态
  }

  return (
    <Paper>
      <Grid container alignItems="center" spacing={2} style={{ padding: '16px' }}>
        <Grid item xs>
          <Grid container justifyContent="flex-end" spacing={2}>
            <Grid item>
              <Button variant="contained" color="primary" onClick={handleConfirm}>
                确定
              </Button>
            </Grid>
            <Grid item>
              <Button variant="outlined" color="secondary" onClick={handleCancel}>
                取消
              </Button>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
      <TableContainer style={{ maxHeight: '70vh' }}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell padding="checkbox">
                {/* 空表头单元格用于多选复选框 */}
              </TableCell>
              {columns.map(col => (
                <TableCell key={col.id}>{col.label}</TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map(row => {
              const isItemSelected = isSelected(row.id);
              return (
                <TableRow
                  key={row.id}
                  hover
                  onClick={() => handleSelectRow(row)}
                  role="checkbox"
                  aria-checked={isItemSelected}
                  selected={isItemSelected}
                >
                  <TableCell padding="checkbox">
                    <Checkbox
                      checked={isItemSelected}
                    />
                  </TableCell>
                  {columns.map(col => (
                    <TableCell key={col.id}>{row[col.id]}</TableCell>
                  ))}
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
        {loading && <CircularProgress style={{ display: 'block', margin: 'auto' }} />}
      </TableContainer>
      <TablePagination
        rowsPerPageOptions={[10, 20, 50]}
        component="div"
        count={rows.length}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
        labelRowsPerPage="每页显示条数"
        labelDisplayedRows={({ from, to, count }) => `${from}–${to} 共 ${count} 条`}
      />
      {/* 添加对话框组件 */}
      <Dialog
        open={openDialog}
        onClose={handleCloseDialog}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">警告</DialogTitle>
        <DialogContent>
          <Typography variant="body1">{dialogMessage}</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDialog} color="primary">
            确定
          </Button>
        </DialogActions>
      </Dialog>
    </Paper>
  );
};

export default App;
